package com.wlq.client;


import com.wlq.WebBoot;
import com.wlq.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


public class ClientHandler implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try{
            HttpRequest request = new HttpRequest(socket);
            File file = new File("./webapps/index.html");
            OutputStream out = socket.getOutputStream();
            String line = "HTTP/1.1 200 OK";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);
            line = "Content-Type: text/html";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);
            line = "Content-Length: "+file.length();
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);
            out.write(13);
            out.write(10);

            FileInputStream indexOut = new FileInputStream(file);
            int len;
            byte[] data = new byte[1024*10];
            while(( len = indexOut.read(data)) != -1 ){
                out.write(data,0,len);
            }
            logger.info("发送响应");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
